package com.fx.attendance.config;

import com.baidu.aip.face.AipFace;
import com.fx.attendance.annotations.OpenAip;
import com.fx.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

/**
 * @description: 人脸识别客户端开启配置类
 * @author: xjr
 * @create: 2020-04-19 16:30
 **/
@Slf4j
public class AipFaceAutoConfigration implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment=environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        String appid=environment.getProperty("baidu.ai.appid");
        String apikey=environment.getProperty("baidu.ai.apikey");
        String secKey=environment.getProperty("baidu.ai.seckey");
        StandardAnnotationMetadata standardAnnotationMetadata= (StandardAnnotationMetadata) annotationMetadata;
        AnnotationAttributes annotationMap= AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(OpenAip.class.getName()));
        if (!annotationMap.getBoolean("open")){
            log.warn("当前人脸功能已关闭");
            return;
        }
        if (StringUtils.isEmpty(appid)|| StringUtils.isEmpty(apikey)||StringUtils.isEmpty(secKey)){
            log.error("请检查配置文件中是否配置百度开放平台者appid,apikey,seckey");
            return;
        }

        BeanDefinitionBuilder beanDefinitionBuilder= BeanDefinitionBuilder.genericBeanDefinition(AipFace.class);
        beanDefinitionBuilder.addConstructorArgValue(appid);
        beanDefinitionBuilder.addConstructorArgValue(apikey);
        beanDefinitionBuilder.addConstructorArgValue(secKey);
        beanDefinitionBuilder.setScope("singleton");
        beanDefinitionRegistry.registerBeanDefinition("aipFace",beanDefinitionBuilder.getBeanDefinition());
    }
}
